import 'dart:collection';
import 'dart:io';

import 'package:get/get.dart';
import 'package:rwini_edit/view/home/logic.dart';

/// 读取文件并解析
getinifile(path) {
  final homelogic = Get.put(HomeLogic());
  File file = File(path);
  file.readAsLines().then((lines) => Ini.fromStrings(lines)).then((Ini value) {
    homelogic.inilist.value = value.a;
    // homelogic.iniback = value.a;
    // print(value.a);
  });
}

/// obj对象转文字 [每一行]
List<String> obj2inifile(RxMap<String, List> obj) {
  List<String> lens = [];
  // print("需要保存！$obj");
  // print(obj.keys);
  for (var k in obj.keys) {
    lens.add("[$k]");
    for (Map<String, dynamic> ls in obj[k]!) {
      lens.add("${ls.keys.first}:${ls.values.first}");
      // print("ls,$ls");
    }
  }

  // print("lens\t $lens");
  return lens;
}

class Ini {
  Ini({
    required this.a,
  });
  HashMap<String, List> a;

  factory Ini.fromStrings(List<String> lines) {
    var linesok = _removeComments(_removeBlankLines(lines));
    // var js = JsonDecoder()
    HashMap<String, List> hm = HashMap();
    var tmplist = [];
    var tmpkey = "";
    for (var a in linesok) {
      if (_sectionPattern.hasMatch(a)) {
        var k = _sectionPattern.matchAsPrefix(a)!.group(1)!;
        // print(k);
        if (tmpkey == "") {
          tmpkey = k;
        } else {
          hm.addAll({tmpkey: tmplist});
          tmplist = [];
          tmpkey = k;
        }
      } else if (_entryPattern.hasMatch(a)) {
        var ms = _entryPattern.matchAsPrefix(a)!;
        tmplist.add({"${ms.group(1)}": "${ms.group(2)}"});
      }
      // debugPrint(a.toString());
    }
    hm.addAll({tmpkey: tmplist});
    tmplist = [];
    tmpkey = "";
    // print(jsonEncode(hm));
    return Ini(a: hm);
  }

  static final RegExp _blankLinePattern = RegExp(r"^\s*$"); //空行
  static final RegExp _commentPattern = RegExp(r"^\s*[;#]"); //注释
  static final RegExp _lineContinuationPattern = RegExp(r"^\s+"); // 空行
  static final RegExp _sectionPattern = RegExp(r"^\s*\[(.*\S.*)]\s*$"); // 【】
  static final RegExp _entryPattern = RegExp(r"^([^:]+):(.*?)$"); //xxx :xxx

  // 去除空行
  static Iterable<String> _removeBlankLines(Iterable<String> source) => source.where((String line) => !_blankLinePattern.hasMatch(line));
  static Iterable<String> _removeComments(Iterable<String> source) => source.where((String line) => !_commentPattern.hasMatch(line));
}
